<template>
  <div>
    <br />
    <div>
      <i class="el-icon-paperclip" style="margin-left: 10px;"/>
      <span> 积分兑换</span>
    </div>
    <el-card style="width: 98%; margin-left: 10px;">
      <br />
      <el-row>
        <el-col :span="20">
          <el-alert style="width: 70%;margin-left: 240px;"
            :title="title" type="success"
            center :closable="false">
          </el-alert>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" icon="el-icon-s-help" size="medium" 
          style="margin-left: 50px;" @click="exchangeBtn">积分兑换</el-button>
        </el-col>
      </el-row>
      <br />
      <el-table :data="exchangeList" height="580"
      row-key="id" :default-expand-all=true
      :default-sort = "{prop: 'date', order: 'descending'}"
      :header-cell-style="{'text-align':'center'}"
      :cell-style="{'text-align':'center'}"
      :row-class-name="tableClass"
      style="width: 98%;margin-left: 20px;margin-top: 20px;">
        <el-table-column prop="date" label="日期" width="250px"></el-table-column>
        <el-table-column prop="id" label="兑换单号" width="200px">
          <template slot-scope="scope">
            <span v-text="scope.row.id" v-if="scope.row.id>0"></span>
          </template>
        </el-table-column>
        <el-table-column prop="cardId" label="会员卡号" width="200px"></el-table-column>
        <el-table-column prop="userName" label="会员姓名" width="180px"></el-table-column>
        <el-table-column prop="waresName" label="兑换商品" width="180px">
          <template slot-scope="scope">
            <el-tag type="danger" style="font-size: 15px;"
            v-text="scope.row.waresName" v-if="scope.row.children===null"/>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="兑换数量" width="100px"></el-table-column>
        <el-table-column prop="integralChange" label="积分变化" width="180px">
          <template slot-scope="scope" v-if="scope.row.children===null">
            <span style="color: black;">- </span>
            <span v-text="scope.row.integralChange" style="color: black;"></span>&nbsp;
            <i class="el-icon-bottom" style="color: red;"></i>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="兑换时间" width="220px"></el-table-column>
      </el-table>
    </el-card>

    <!-- 积分兑换对话框 -->
    <el-dialog title="积分兑换" :visible.sync="exchangeDialog" width="40%" @close="closeExchangeDialog">
      <el-form :model="cardForm" :rules="cardRules" ref="cardFormRef" label-width="100px">
        <el-row>
            <el-col :span="12">
              <el-form-item label="会员卡号" prop="id" style="width: 90%;">
                <el-cascader v-model="cardForm.id" :options="userList" :props="props" filterable
                :show-all-levels="false" @change="changeIntegral"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员卡积分" prop="integral" style="width: 90%;">
                <el-input v-model="cardForm.integral" readonly @focus="warning"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-form>
      <el-form :model="waresForm" :rules="waresRules" ref="waresFormRef" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="兑换商品" prop="id">
              <el-select v-model="waresForm.id" filterable @change="getIntegral">
                <el-option v-for="wares in waresList" :key="wares.id" :label="wares.waresName" :value="wares.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="兑换数量" prop="num">
              <el-input-number v-model="waresForm.num" @change="handleChange" :min="1">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品积分" prop="integral" style="width: 90%;">
              <el-input v-model="waresForm.integral" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="积分总计" prop="integralSum" style="width: 90%;">
              <el-input v-model="waresForm.integralSum" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exchangeDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveExchange">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    created(){
      this.getUserAndCard()
      this.getCardList()
      this.getWaresList()
      this.getExchangeList()
    },
    data(){
      return{
        title:'您 好 ， 欢 迎 进 入 积 分 兑 换 界 面 ！',
        userList:[],
        cardList:[],
        waresList:[],
        exchangeList:[],
        exchangeDialog:false,
        waresForm:{
          id:null,
          num:1
        },
        cardForm:{
          integral:null
        },
        //定义级联选择项
        props: {
          //定义子节点菜单展开方式
          expandTrigger: "hover",
          value: "userName", //选中数据的value值
          label: "userName", //选中数据展现名称
          children: "children" ,//自选项数据
          emitPath: false    //只获取最后一个节点的值
        },
        cardRules: {
          id: [{
            required: true,
            message: '请选择会员卡',
            trigger: 'blur'
          }],
          integral: [{
              required: true,
              message: '会员卡积分不能为空',
              trigger: 'blur'
            }
          ]
        },
        waresRules: {
          id: [{
            required: true,
            message: '请选择兑换商品',
            trigger: 'blur'
          }],
          num: [{
            required: true,
            message: '请选择兑换数量',
            trigger: 'blur'
          }],
          integral: [{
            required: true,
            message: '商品积分不能为空',
            trigger: 'blur'
          }],
          integralSum: [{
            required: true,
            message: '积分总计不能为空',
            trigger: 'blur'
          }],
        }
      }
    },
    methods:{
      async getUserAndCard(){
        const {data: result} =await this.$http.get(`user/getUserAndCard`)
        this.userList=result.data
      },
      async getCardList(){
        const {data: result} =await this.$http.get(`card/list?query=`+'')
        this.cardList=result.data
      },
      async getWaresList(){
        const {data: result} =await this.$http.get(`wares/getWaresList`)
        this.waresList=result.data
      },
      async getExchangeList(){
        const {data: result} =await this.$http.get(`exchange/getExchangeList`)
        this.exchangeList=result.data
      },
      tableClass({row}) {
        if (row.children !== null) {
          return 'primary-row'
        }
        return ''
      },
      closeExchangeDialog(){
        this.$refs.cardFormRef.resetFields()
        this.$refs.waresFormRef.resetFields()
        this.cardForm={
          integral:null
        }
        this.waresForm={
          id:null,
          num:1
        }
      },
      warning() {
        this.$notify.warning({
          title: '注意',
          dangerouslyUseHTMLString: true,
          message: '<div>会员卡积分无需手动输入</div><div>选择会员卡后，积分会自动显示</div>',
          offset: 100
        });
      },
      changeIntegral(id){
        this.$refs.cardFormRef.resetFields()
        this.cardForm.id=id
        for(let card of this.cardList){
          if(this.cardForm.id===card.id){
            this.cardForm.integral=card.integral
            break
          }
        }
      },
      async getIntegral(id){
        this.$refs.waresFormRef.resetFields()
        let num=this.waresForm.num
        const {data: result} = await this.$http.get(`wares/getWaresById?id=${id}`)
        this.waresForm=result.data
        this.waresForm.integralSum=this.waresForm.integral * num
        this.waresForm.num=num
      },
      handleChange(num){
        if(this.waresForm.id !== null){
          this.waresForm.integralSum=this.waresForm.integral * num
        }
        console.log(this.waresForm)
      },
      exchangeBtn(){
        this.exchangeDialog=true
      },
      async saveExchange(){
        this.$refs.cardFormRef.validate(async valid1 => {
          this.$refs.waresFormRef.validate(async valid2 => {
            //如果校验失败 则停止数据
            if (!valid1||!valid2) return
            if (this.cardForm.integral < this.waresForm.integral * this.waresForm.num) {
              this.$message.error("会员卡积分不足，无法兑换商品!")
              return
            }
            this.cardForm.integralSum=this.waresForm.integralSum
            let form = {
              card: this.cardForm,
              wares: this.waresForm
            }
            const {data: result} =await this.$http.post(`exchange/saveExchange`,form)
            if(result.status !== 200 ) return this.$message.error("积分兑换失败!")
            // this.$message.success("积分兑换成功!")
            this.title=`兑 换 成 功 ！ ${this.cardForm.id} 会 员 卡 已 成 功 兑 换 “ ${this.waresForm.waresName} ” 商 品 ！`
            this.getCardList()
            this.getExchangeList()
            this.exchangeDialog=false
          })
        })
      }
    }
  }
</script>

<style>
  .el-table .primary-row {
    background: #f4f7f9;
  }
</style>
